package com.cooba.activitys.integral;

import android.content.Intent;
import android.graphics.drawable.ColorDrawable;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ImageButton;
import android.widget.ListView;
import android.widget.PopupWindow;
import android.widget.TextView;
import android.widget.Toast;

import com.cooba.R;
import com.cooba.adapter.GoodsExchangeAdapter;
import com.cooba.application.MyApplication;
import com.cooba.bean.GoodsExchangeBean;
import com.cooba.pullTorefresh.PullToRefreshBase;
import com.cooba.pullTorefresh.PullToRefreshListView;
import com.cooba.utils.ServerURL;
import com.cooba.utils.Utils;
import com.cooba.views.loadview.LoadViewHelper;
import com.google.gson.Gson;
import com.google.gson.JsonSyntaxException;
import com.lidroid.xutils.HttpUtils;
import com.lidroid.xutils.exception.HttpException;
import com.lidroid.xutils.http.RequestParams;
import com.lidroid.xutils.http.ResponseInfo;
import com.lidroid.xutils.http.callback.RequestCallBack;
import com.lidroid.xutils.http.client.HttpRequest;
import com.umeng.analytics.MobclickAgent;
import com.umeng.message.PushAgent;

import java.util.ArrayList;
import java.util.List;

/**
 * Created by Administrator on 2016/6/13.
 */
public class GoodsExchangeActivity extends AppCompatActivity implements View.OnClickListener {
    private ImageButton back_ib;
    private TextView mFilter_tv;
    private PullToRefreshListView rListView;
    private GoodsExchangeAdapter mAdapter;
    private List<GoodsExchangeBean.productsInfo> productsList;
    private HttpUtils httpUtils;
    private RequestParams params;
    private String next_key = "0";
    private GoodsExchangeBean goodsExchangeBean;
    private PopupWindow mFilterChoosePop;
    private LoadViewHelper helper;
    private boolean mIsFirstLoad=true;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_goods_exchange);

        PushAgent.getInstance(this).onAppStart();

        initView();
        initPopUpWindow();
        getGoodsData(true);
    }

    private void initPopUpWindow() {
        View chooseView =this.getLayoutInflater().inflate(R.layout.popup_dialog, null);
        mFilterChoosePop = new PopupWindow(chooseView, ViewGroup.LayoutParams.WRAP_CONTENT,
                ViewGroup.LayoutParams.WRAP_CONTENT);
        mFilterChoosePop.setFocusable(true);
        mFilterChoosePop.setOutsideTouchable(true);
        mFilterChoosePop.setBackgroundDrawable(new ColorDrawable());

        chooseView.findViewById(R.id.tv_entity).setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {
                if (mFilterChoosePop != null) {
                    mFilterChoosePop.dismiss();
                }
                mAdapter.getFilter().filter("0");
            }
        });

        chooseView.findViewById(R.id.tv_virtual).setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {
                if (mFilterChoosePop != null) {
                    mFilterChoosePop.dismiss();
                }
                mAdapter.getFilter().filter("1");
            }
        });

        chooseView.findViewById(R.id.tv_flow).setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {
                if (mFilterChoosePop != null) {
                    mFilterChoosePop.dismiss();
                }
                mAdapter.getFilter().filter("2");
            }
        });
    }
    private void showFilterChoosePop(View view) {
        if (mFilterChoosePop == null) {
            return;
        }
        if (mFilterChoosePop.isShowing()) {
            mFilterChoosePop.dismiss();
        } else {
            mFilterChoosePop.showAsDropDown(view);
        }
    }
    private void initView() {
        productsList = new ArrayList<>();
        back_ib = (ImageButton) findViewById(R.id.goods_exchange_back_ib);
        mFilter_tv= (TextView) findViewById(R.id.goods_exchange_filter);
        initPullTorefresh();
        helper=Utils.initLoadViewHelper(rListView);
        back_ib.setOnClickListener(this);
        mFilter_tv.setOnClickListener(this);

    }

    private void initPullTorefresh() {
        rListView = (PullToRefreshListView) findViewById(R.id.goods_exchange_lv);
        rListView.setPullRefreshEnabled(false);
        rListView.setPullLoadEnabled(true);
        rListView.setScrollLoadEnabled(true); //设置滚动加载可用
        mAdapter = new GoodsExchangeAdapter(this, productsList);
        rListView.getRefreshableView().setAdapter(mAdapter);
        rListView.setOnRefreshListener(new PullToRefreshBase.OnRefreshListener<ListView>() {
            @Override
            public void onPullDownToRefresh(PullToRefreshBase<ListView> refreshView) {//下拉刷新

            }

            @Override
            public void onPullUpToRefresh(PullToRefreshBase<ListView> refreshView) {//上拉加载
                getGoodsData(false);
            }
        });
        rListView.getRefreshableView().setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                MyApplication application = MyApplication.getMyApplication();
                if (!application.getIsInCar() && mAdapter.getList().get(position).getType().equals("2")) {
                    Toast.makeText(GoodsExchangeActivity.this, "当前环境不可兑换!", Toast.LENGTH_SHORT).show();
                    return;
                }
                if (mAdapter.getList().get(position).getNum().equals("0")) {
                    Toast.makeText(GoodsExchangeActivity.this, "当前数量为0，不可兑换!", Toast.LENGTH_SHORT).show();
                    return;
                }
                Intent intent = new Intent(GoodsExchangeActivity.this, ComfirmExchangeActivity.class);
                Bundle bundle = new Bundle();
                bundle.putString("goods_id", mAdapter.getList().get(position).getId());
                bundle.putString("goods_icon", mAdapter.getList().get(position).getIcon());
                bundle.putString("goods_name", mAdapter.getList().get(position).getName());
                bundle.putString("goods_num", mAdapter.getList().get(position).getNum());
                bundle.putString("goods_need_integral", mAdapter.getList().get(position).getIntegral_num());
                bundle.putString("goods_public_date", mAdapter.getList().get(position).getPublic_date());
                bundle.putString("goods_valid_date", mAdapter.getList().get(position).getValid_date());
                bundle.putString("goods_ex_type", mAdapter.getList().get(position).getEx_type());
                bundle.putString("goods_desc", mAdapter.getList().get(position).getDesc());
                intent.putExtra("goods_data", bundle);
                startActivity(intent);
            }
        });
    }

    private void getGoodsData(final boolean isFirst) {
        if (mIsFirstLoad){
            helper.showLoading("正在加载...");
        }
        httpUtils = new HttpUtils();
        params = new RequestParams();
        Log.d("wei", "next_key" + next_key);
        //params.addBodyParameter("type","");
        params.addBodyParameter("next_key", next_key);
        params.addBodyParameter("page_size", "10");
        String urlgoodsexchangelist = ServerURL.httpUrl + ServerURL.goodsExchangeList;
        httpUtils.send(HttpRequest.HttpMethod.POST, urlgoodsexchangelist, params, new RequestCallBack<String>() {
            @Override
            public void onFailure(HttpException arg0, String arg1) {
                Log.e("wei", "获取商品列表失败");
                Toast.makeText(GoodsExchangeActivity.this, "无网络!", Toast.LENGTH_SHORT).show();
                rListView.setHasMoreData(false);
                rListView.onPullDownRefreshComplete();
                rListView.onPullUpRefreshComplete();
            }

            @Override
            public void onSuccess(ResponseInfo<String> responseInfo) {
                Log.e("wei", "获取商品列表成功" + responseInfo.result);
                // Log.d("wei","状态吗"+responseInfo.statusCode);
                try {
                    goodsExchangeBean = new Gson().fromJson(responseInfo.result, GoodsExchangeBean.class);
                    if (goodsExchangeBean.getProductsList() != null && goodsExchangeBean.getProductsList().size() > 0) {
                        if (isFirst) {
                            mAdapter.setList(goodsExchangeBean.getProductsList());
                        } else {
                            mAdapter.addMoreData(goodsExchangeBean.getProductsList());
                        }
                        if (goodsExchangeBean.getNext_key() == null) {
                            next_key = String.valueOf(goodsExchangeBean.getProductsList().size() + Integer.parseInt(next_key));
                        } else {
                            next_key = goodsExchangeBean.getNext_key();
                        }
                        if (goodsExchangeBean.getProductsList().size() < 10) {
                            rListView.setHasMoreData(false);
                        }
                        mIsFirstLoad = false;
                        helper.restore();
                    } else {
                        if (isFirst) {
                            helper.showEmpty("暂时没有数据", "重新加载", false, null);
                        } else {
                            Toast.makeText(GoodsExchangeActivity.this, "没有更多数据啦", Toast.LENGTH_SHORT).show();
                        }
                    }
                } catch (JsonSyntaxException e) {
                    e.printStackTrace();
                } finally {

                    rListView.onPullDownRefreshComplete();
                    rListView.onPullUpRefreshComplete();
                }

            }
        });
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.goods_exchange_back_ib:
                finish();
                break;
            case R.id.goods_exchange_filter:
                showFilterChoosePop(v);
                break;
            default:
                break;
        }
    }

    public void onResume() {
        super.onResume();
        MobclickAgent.onResume(this);
    }
    public void onPause() {
        super.onPause();
        MobclickAgent.onPause(this);
    }
}
